#!/bin/sh
#
# Copyright (C) 2000-2025 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
# Test the FDCallsDir feature with many clients
#
TestName="fdcallsdir-many-clients-test"
JobName=backup
. scripts/functions

scripts/cleanup
scripts/copy-confs

cleanup_fd()
{
    while ! mkdir  $tmp/pid/started 2> /dev/null
    do
        sleep 1
    done

    for i in $tmp/pid/*.pid
    do
        kill `cat $i`
    done
    rmdir $tmp/pid/started
}

#
# Zap out any schedule in default conf file so that
#  it doesn't start during our test
#
outf="$tmp/sed_tmp"
echo "s%  Schedule =%# Schedule =%g" >${outf}
cp $scripts/bacula-dir.conf $tmp/1
sed -f ${outf} $tmp/1 >$scripts/bacula-dir.conf


# Setup console on FD
[ x$FORCE_FDCALLS = x ] && $bperl -e 'setup_fdcallsdir()'

change_jobname BackupClient1 $JobName

start_test

# Get the current client name (seems to be hostname)
client=`$bin/bdirjson -c $conf/bacula-dir.conf -r client -D -l Name | awk '/Name/ { print $2; exit}' | sed 's/"//g'`

# Get the Client and the Console associated with the client
print_debug "Get configuration for client $client"
$bperl -e "extract_resource('$conf/bacula-dir.conf', 'Client', '$client')"  > $tmp/1
$bperl -e "extract_resource('$conf/bacula-dir.conf', 'Console', '$client')" >> $tmp/1

# We store all PIDs in this directory for a nice cleanup at the end
mkdir $tmp/pid
trap 'cleanup_fd' EXIT INT TERM

# We generate X client and console resources
max=50
for i in $(seq 1 $max)
do
    sed "s/${client}/${client}-${i}/g" $tmp/1 >> $conf/bacula-dir.conf
    $bperl -e "add_attribute('$conf/bacula-dir.conf', 'FDPort', \$BASEPORT + 10 + $i, 'Client', '${client}-${i}')"

    sed "s/${client}/${client}-${i}/g" $conf/bacula-fd.conf >> $tmp/bacula-fd.conf.${client}-${i}
    $bperl -e "add_attribute('$tmp/bacula-fd.conf.${client}-${i}', 'FDport', \$BASEPORT + 10 + $i)"
    $bperl -e "add_attribute('$tmp/bacula-fd.conf.${client}-${i}', 'Pid Directory', '$tmp/pid', 'FileDaemon')"
    (sleep 5 ; $bin/bacula-fd -c $tmp/bacula-fd.conf.${client}-${i} ; print_debug "Starting ${client}-${i}..." ) &
done

cat <<END_OF_DATA >$tmp/bconcmds
@output /dev/null
messages
@$out $tmp/log3.out
status client=$client
status client=${client}-1
status client=${client}-2
show client
@$out $tmp/log1.out
setdebug level=4 storage=File1
label volume=TestVolume001 storage=File1 pool=File slot=1 drive=0
run job=$JobName yes
run job=$JobName client=${client}-1 yes
run job=$JobName client=${client}-2 yes
run job=$JobName client=${client}-3 yes
run job=$JobName client=${client}-4 yes
run job=$JobName client=${client}-${max} yes
wait
messages
show client
@# 
@# now do a restore
@#
@$out $tmp/log2.out  
setdebug level=4 storage=File1
restore where=$tmp/bacula-restores client=$client select all done
yes
wait
messages
quit
END_OF_DATA

run_bacula
check_for_zombie_jobs storage=File1 client=$client
stop_bacula

trap '' EXIT INT TERM
cleanup_fd

check_two_logs
check_restore_diff
end_test
